package net.xdclass.onlinexdclass.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.onlinexdclass.utils.JWTUtils;
import net.xdclass.onlinexdclass.utils.JsonDate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 定义拦截器
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    /**
     * 进入到Controller之前的方法
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取经过nginx反向代理的客户端真实IP(用于获取白名单)
        //在 Nginx 的配置文件里，找到你 Java 项目的配置，在 location 里添加以下代码：
        //proxy_set_header X-Real-IP $remote_addr;
        //proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        //然后使用nginx -s reload重启即可
        String ip = request.getHeader("x-forwarded-for");
        log.info("x-forwarded-for = {}", ip);
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            log.info("Proxy-Client-IP = {}", ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            log.info("WL-Proxy-Client-IP = {}", ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            log.info("request.getRemoteAddr = {}", ip);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("访问接口服务的客户端IP是{},时间是{}", ip, simpleDateFormat.format(new Date()));

        try {
            String accessToken = request.getHeader("token");
            if (accessToken == null) {
                accessToken = request.getParameter("token");
            }

            if (StringUtils.isNotBlank(accessToken)) {
                Claims claims = JWTUtils.checkJWT(accessToken);
                if (null == claims) {
                    //告诉登录过期，重新登录
                    sendJsonMessage(response, JsonDate.bulidSuccess("登录过期，重新登录"));
                    return false;
                }
                Integer id = (Integer) claims.get("id");
                String name = (String) claims.get("name");

                request.setAttribute("user_id", id);
                request.setAttribute("name", name);
                return true;
            }
        } catch (Exception e) {
            //登录失败
            e.printStackTrace();
        }

        sendJsonMessage(response, JsonDate.bulidSuccess("登录过期，重新登录"));
        return false;
    }


    public static void sendJsonMessage(HttpServletResponse response, Object object) {
        try {
            //转换成json的工具类
            ObjectMapper objectMapper = new ObjectMapper();

            response.setContentType("application/json; charset=utf-8");
            //回写到前端
            PrintWriter writer = response.getWriter();
            writer.println(objectMapper.writeValueAsString(object));
            writer.close();
            //刷新一下
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
